package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.domain.TbOrder;
import com.bwie.domain.TbOrderDetail;
import com.bwie.domain.TbProd;
import com.bwie.domain.TbUser;
import com.bwie.mapper.TbOderMapper;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.service.IProductService;
import com.bwie.service.IUserService;
import com.bwie.service.TbOrderService;
import com.bwie.state.OrderStatusEnum;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.PieDataVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2024/10/16 13:58
 */

@Service
public class TbOrderServiceImpl implements TbOrderService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    TbOderMapper tbOderMapper;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    IProductService iProductService;

    @Autowired
    IUserService iUserService;

    @Autowired
    HttpServletRequest request;

    @Override
    public R getUserById(Integer userId) {

        String url = "http://localhost:9001/user/user/getUserById/" + userId;
        R r = restTemplate.getForObject(url, R.class);

        return r;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R buy(ArrayList<TbProd> tbProds) {
        // 动态计算商品价格
        Double amount = 0.0;
        for (TbProd tbProd : tbProds) {
            amount += tbProd.getProdPrice() * tbProd.getProdCount();
        }
        System.out.println("订单金额：" + amount);

        // 使用Rest'Tempate检查库存
        for (TbProd tbProd : tbProds) {
            // 方法1： restTemplate
//            String url = "http://localhost:9011/prod/prod/checkStock/" + tbProd.getProdId() + "/" + tbProd.getProdCount();
//            R r = restTemplate.getForObject(url, R.class);
//            if(!r.getFlag()) {
//                return r;
//            }

            // 方法2： Feign
            R r = iProductService.checkStock(tbProd.getProdId(), tbProd.getProdCount());
            if(!r.getFlag()) {
                return r;
            }
        }

        // 生成订单
        TbOrder tbOrder = new TbOrder();
        // 雪花算法生成订单ID
        tbOrder.setOrderNo(IdUtil.getSnowflake(1, 1).nextId());
        tbOrder.setOrderAmount(amount);
        tbOrder.setOrderStatus(0);
        tbOrder.setOrderName(tbProds.get(0).getProdName() + "等");
        tbOrder.setCreateTime(new Date());
        // 获取购买人的ID：按理说是从token中获取的，这里直接写死
        tbOrder.setUserId(1);

        tbOderMapper.insert(tbOrder);

        // 写入订单明细
        for (TbProd tbProd : tbProds) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();
            tbOrderDetail.setOrderId(tbOrder.getOrderId());
            tbOrderDetail.setProdId(tbProd.getProdId());
            tbOrderDetail.setProdName(tbProd.getProdName());
            tbOrderDetail.setProdCount(1);
            tbOrderDetail.setProdPrice(tbProd.getProdPrice());
            tbOrderDetail.setProdAmount(tbProd.getProdPrice() * tbProd.getProdCount());

            tbOrderDetailMapper.insert(tbOrderDetail);
        }

        return R.OK();
    }

    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {
        //--1 构造分页信息
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        //--2 查询列表并返回
//        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
//        if(!StringUtils.isEmpty(pageInfoVo.getKeyWord())) {
//            wrapper.lambda().like(TbOrder::getOrderName, pageInfoVo.getKeyWord());
//        }
//        wrapper.lambda().orderByDesc(TbOrder::getOrderId);
        Page<TbOrder> tbOrderPage = tbOderMapper.getOrderListByPage(page, pageInfoVo.getKeyWord(), pageInfoVo.getTypeId());

        return R.OK(tbOrderPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R userPayByOrderId(Integer orderId) {
        //--1 获取订单信息
        TbOrder tbOrder = tbOderMapper.selectById(orderId);
        if(tbOrder == null) {
            return R.ERROR(500, "订单不存在");
        }

        //--2 获取用户ID
        String token = request.getHeader("token");
        if(token == null) {
            return R.ERROR(500, "请先登录再支付");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);

        //--3 扣减余额
        R r1 = iUserService.subUserMoney(userId, tbOrder.getOrderAmount());
        if(r1.getCode() != 200) {
            System.out.println(r1.getMsg());
            return r1;
        }

        //--4 更新订单状态
        tbOrder.setOrderStatus(OrderStatusEnum.WAIT_DELIVERY.getCode());
        tbOderMapper.updateById(tbOrder);

        return R.OK();
    }

    @Override
    public R getProdSailAmount() {

        List<PieDataVo> prodSailAmount = tbOderMapper.getProdSailAmount();

        return R.OK(prodSailAmount);
    }
}
